#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time  : 2018/7/17 20:56
# @Author : 
# @File  : addline.py
import os
import sys
import re
import time
##使用方法：
# python addline.py 240 filename 165 directory runnum
## 如：python addline.py 240 /home/soft/2018-7-17/activityIqiyi_766bb10bd811e40732cf79dffde9a904_20180717.tar.gz 165 /home/soft 190122


##拷贝文件
def cpfile(source_host,source_dir, runnum):
  os.system("mkdir -p /sx/%s" % (runnum))
  os.system("scp %s:%s /sx/%s " % (source_host,source_dir, runnum))

##解压文件
def tarfile(source_dir,runnum):

  target_test = re.split(r'/', source_dir)
  print(target_test[-1])
  os.system(
    "tar zxvf /sx/%s/%s -C /sx/%s/" % (runnum,target_test[-1], runnum))
  time.sleep(1) #休眠一秒 因为同步脚本获取日志需要一秒钟

# 同步文件
def syncfile(filename, runnum,target_host):

  os.system("ssh %s 'mkdir -p /home/soft/sx/%s'" % (target_host,runnum))
  os.system("scp -r /sx/%s/%s %s:/home/soft/sx/%s/" %
       (runnum, filename,target_host,runnum))
  # os.system("ssh 165 'sudo -u apps sh /home/soft/bcp_web.sh /home/soft/sx/%s/%s /home/apps/ananetest/%s'" %
  #      (runnum, filename, filename))

def delfile(runnum):
  os.system("mv /sx/%s /sx/wc"%(runnum))

def main():
  source_host=sys.argv[1] #源主机ip
  source_dir=sys.argv[2] #源主机文件
  target_host=sys.argv[3] #目标主机ip
  target_dir=sys.argv[4] #目标主机文件
  runnum=sys.argv[5] #oa流水号

  cpfile(source_host,source_dir,runnum) #将文件从源主机拷贝到堡垒机
  tarfile(source_dir,runnum) #解压文件

#获得解压文件名
  with open('/var/log/sx.log', 'r') as f:
    lines = f.readlines()
    last_line = lines[-1]
    print(last_line)
    filename = re.split(r'/', last_line)
    print(filename[3])

  syncfile(filename[3], runnum,target_host) #将文件同步到目标主机
  delfile(runnum) #将堡垒机文件移动到完成目录

if __name__ == '__main__':
  main()

